package progress.exa4;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ByteArrayInputStreamStudy {

    public static void main(String[] args) throws IOException {
        readStudy();
    }

    public static void readStudy() throws IOException {
        //定义字节数组输入流的源
        byte[] bytes = "我是四郎".getBytes(StandardCharsets.UTF_8);
        //根据源创建字节数组输入流
        ByteArrayInputStream inputStream = null;
        try{
            inputStream = new ByteArrayInputStream(bytes);
            byte[] result = new byte[0];
            //读取源bytes中的数据
            int n;
            while ((n=inputStream.read())!=-1) {
                System.out.println("读取到字符："+(char)n);
                byte[] resultTemp = new byte[result.length+1];
                for(int i=0;i<result.length;i++) {
                    resultTemp[i] = result[i];
                }
                resultTemp[result.length] = (byte) n;
                result = resultTemp;
            }
            System.out.println("为了读到正确的字符串，我不得不增加了很多操作，这也是字节流的缺点" );
            System.out.println("最后正确的字符串为："+new String(result));
        }catch (Exception e) {
             e.printStackTrace();
        }finally {
            if(inputStream!=null) {
                inputStream.close();
            }
        }
    }


}
